package util;

import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class VerifyUtil {
	private static final String SIGN = "LYZ"; //密钥
	
	public static String verify(String token) {
		//使用这个方法获取token里面的用户信息
		try {
	        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SIGN))
	                .build()
	                .verify(token);

	        // 获取载荷中的自定义字段信息
	        Map<String, Claim> claims = jwt.getClaims();
	        Claim userInfoClaim = claims.get("userInfo");

	        // 判断是否存在自定义字段
	        if (userInfoClaim != null) {
	            // 获取用户信息和用户ID
	            Map<String, Object> userInfo = userInfoClaim.asMap();
	            String userId = (String) userInfo.get("userId");
	            return userId;
	        } else {
	            return null;
	        }
	    } catch (JWTVerificationException e) {
	        // 验证失败，token无效
	        e.printStackTrace();
	    }
		return null;
	}
}
